<?php

require_once($WSC->get_site_inc_dir().'modules/tangra_cms/_sys/tcms_admin_web_page_wed_ua.class.php');
require_once($WSC->get_site_inc_dir().'modules/tangra_cms/classes/vpage/tcms_vpage_dbc.class.php');
require_once($WSC->get_site_inc_dir().'modules/tangra_cms/classes/vpage/tcms_vpage_template_dbc.class.php');
require_once($WSC->get_site_inc_dir().'modules/tangra_cms/classes/vpage/tcms_vpt_ci_dbc.class.php');
require_once($WSC->get_site_inc_dir().'modules/tangra_cms/classes/vpage/tcms_vpage_ci_dbc.class.php');
require_once($WSC->get_site_inc_dir().'modules/tangra_cms/classes/vpage/tcms_vpage_category_dbc.class.php');

require_once($WSC->get_site_inc_dir().'modules/tangra_cms/classes/vpage/tcms_vpage_system_attribute_dbc.class.php');
require_once($WSC->get_site_inc_dir().'modules/tangra_cms/classes/vpage/tcms_vpt_system_attribute_dbc.class.php');
require_once($WSC->get_site_inc_dir().'modules/tangra_cms/classes/settings/tcms_settings_cache_dbc.class.php');
require_once($WSC->get_site_inc_dir().'modules/admin_panel/classes/admin_user/admin_user_dbc.class.php');
require_once($WSC->get_site_inc_dir().'modules/tangra_cms/classes/category/tcms_category_dbc.class.php');
require_once($WSC->get_site_inc_dir().'modules/tangra_cms/classes/menu/item_types/tcms_menu_item_vpage_dbc.class.php');


abstract class VPage_Manage_WP_Abs extends TCMS_Admin_Web_Page_WED_UA {
	private $vpage;
	private $vpage_template;


	abstract protected function _manage();


	public function get_vpage() {
		return $this->vpage;
	}


	public function get_vpage_template() {
		return $this->vpage_template;
	}


	public function create_view($name = 'default') {
		$ret = new TCMS_Admin_Page_View($this, $name, 'modules/tangra_cms/pages/_vpage/_vpt/');

		return $ret;
	}


	protected function init_transit_vars() {
		$this->add_transit_var('category');
	}


	public function init() {
		parent::init();

		$v = $this->create_view();
		$this->add_view($v);

		$v2 = $this->create_view('not_exist');
		$this->add_view($v2);

		$manage_event = new Web_Event_Simple_Int('manage', Tangra_Parameter_Method::GET, 'manage');
		$this->wed->add_wed_event_action_pair($manage_event, 'manage_event');

		$this->prepare_preview_code();
	}


	protected function manage_event($vpage_id) {
		$dbc = $this->get_dbc();

		$vpage = new TCMS_VPage_DBC();

		if ($vpage->load_by_id($dbc, $vpage_id)) {
			$this->export('vpage', $vpage);

			$this->vpage = $vpage;
			$vp_template = new TCMS_VPage_Template_DBC();
			if ($vp_template->load_by_id($dbc, $vpage->get_template())) {
				$this->vpage_template = $vp_template;
				$this->export_common();

				$this->call_subevent();

				$view = $this->_manage($vpage);
			} else {
				$this->export('template_missing', 1);
				$view = $this->get_view('not_exist');
			}
		} else {
			$view = $this->get_view('not_exist');
		}

		return $view;
	}


	private function call_subevent() {
		$context = $this->get__context();

		if ($context->exists_in_get('cache_clear')) {
			$this->cache_clear_subevent();
		} elseif($context->exists_in_get('cache_lock')) {
			$this->cache_lock_subevent($context->get_from_get('cache_lock'));
		} elseif($context->exists_in_get('unlink')) {
			$this->unlink_subevent($context->get_from_get('unlink'));
		} elseif($context->exists_in_get('link') && $context->exists_in_get('linkto')) {
			$this->link_subevent($context->get_from_get('link'), $context->get_from_get('linkt'));
		} elseif($context->exists_in_get('online')) {
			$this->online_subevent($context->get_from_get('online'));
		}
	}


	private function cache_clear_subevent($params) {
		$dbc = $this->get_dbc();

		$vpage = $this->get_vpage();

		$cache_path = str_replace('/', '-', $vpage->get_path()).'-vp'.$vpage->get_id().'.html';
		$cache_file = $this->get__config()->get_scratch_dir().'tcms_cache/'.$cache_path;
		if (file_exists($cache_file)) {
			unlink($cache_file);
		}
	}


	protected function cache_lock_subevent($lock) {
		$dbc = $this->get_dbc();

		try {
			$dbc->start_trans();

			$vpage = $this->get_vpage();
			$vpage->set_cache_locked($lock);
			$vpage->save($dbc);

			$dbc->complete_trans();
		} catch (Exception $e) {
			$dbc->fail_trans();
			$dbc->complete_trans();
			throw $e;
		}
	}


	protected function unlink_subevent($unlink) {
		tangra_if_not_int_throw_e($unlink);

		$dbc = $this->get_dbc();
		try {
			$dbc->start_trans();
			TCMS_VPage_CI_DBC::delete($dbc, $unlink);
			$current_user = $this->get_user();
			TCMS_VPage_DBC::update_last_modified($dbc, $this->get_vpage()->get_id(), $current_user->get_id());
			$dbc->complete_trans();
		} catch (Exception $e) {
			$dbc->fail_trans();
			$dbc->complete_trans();
			throw $e;
		}
	}


	protected function link_subevent($ci_id, $vpt_ci_id) {
		$vpage_id = $this->get_vpage()->get_id();

		$vpt_ci = new TCMS_VPT_CI_DBC();
		$dbc = $this->get_dbc();
		if ($vpt_ci->load_by_id($dbc, $vpt_ci_id)) {
			if (TCMS_VPage_CI_DBC::is_unique_for_page($dbc, $vpage_id, $vpt_ci_id)) {
				$ci = new TCMS_VPage_CI_DBC();
				$ci->set_vpage($vpage_id);
				$ci->set_t_ci_id($vpt_ci_id);
				$ci->set_type($vpt_ci->get_ci_type());
				$ci->set_ci_id($ci_id);

				try {
					$dbc->start_trans();
					$ci->save($dbc);
					$current_user = $this->get_user();
					TCMS_VPage_DBC::update_last_modified($dbc, $vpage_id, $current_user->get_id());
					$dbc->complete_trans();
				} catch (Exception $e) {
					$dbc->fail_trans();
					$dbc->complete_trans();
					throw $e;
				}
			}
		}
	}


	protected function online_subevent($online) {
		$vpage_id = $this->get_vpage()->get_id();

		$dbc = $this->get_dbc();

		$vpage = new TCMS_VPage_DBC();
		if ($vpage->load_by_id($dbc, $vpage_id)) {
			if ((boolean)$online != $vpage->get_online()) {
				$current_user = $this->get_user();
				try {
					$dbc->start_trans();
					TCMS_VPage_DBC::set_status_online($dbc, $vpage_id, $online, $current_user->get_id());
					$vpage = $this->get_vpage();
					$vpage->set_online($online);
					$dbc->complete_trans();
				} catch (Exception $e) {
					$dbc->fail_trans();
					$dbc->complete_trans();
					throw $e;
				}
			}
		}
	}


	protected function default_event() {
		throw new Tangra_User_Exception('Expecting manage parameter.');
	}


//	private function can_go_online() {
//		$dbc = $this->get_dbc();
//
//		$t_sas = TCMS_VPT_System_Attribute_DBC::select_vpt_sas_for_template($dbc, $vpage->get_template());
//		$page_system_attributes = TCMS_VPage_System_Attribute_DBC::load_all_for_vpage($dbc, $vpage_id);
//		$missing_required_sa = false;
//		foreach($t_sas as $key => &$tas) {
//			if (!array_key_exists($tas['id'], $page_system_attributes)) {
//				if ($tas['required']) {
//					$missing_required_sa = true;
//				}
//			}
//		}
//
//
//		$t_cis = TCMS_VPT_CI_DBC::load_vpt_cis_for_template($dbc, $vp_template->get_id());
//		$vp_cis = TCMS_VPage_CI_DBC::load_cis_for_page($dbc, $vpage_id);
//		$missing_required_ci = false;
//		foreach($t_cis as $key => &$tis) {
//			if (!array_key_exists($tis['id'], $vp_cis)) {
//				if ($tis['required']) {
//					$missing_required_ci = true;
//				}
//			}
//		}
//
//
//		return !($missing_required_sa || $missing_required_ci);
//	}


	private function prepare_preview_code() {
		$svm = $this->get_svm();
		if ($svm->is_global_var_registered('preview_code')) {
			$preview_code = $svm->get_global_var('preview_code');
		} else {
			$preview_code = md5(mt_rand());
			$svm->register_global_var('preview_code');
			$svm->set_global_var('preview_code', $preview_code);
		}

		$this->export('_tcms_preview_code', $preview_code);
	}


	/**
	 * Loads last_modified using template. Category pages' last_modified have to be same as latest last_modified of page in this category
	 *
	 * @param TCMS_VPage_Template_DBC $template
	 * @param TCMS_VPage_DBC $vpage
	 * @return string Datetime of last modification
	 */
	private function get_last_modified(TCMS_VPage_Template_DBC $template, TCMS_VPage_DBC $vpage) {
		$dbc = $this->get_dbc();

		require_once($this->get__config()->get_site_inc_dir().$template->get_wp_path());
		$page_class = $template->get_wp_class_name();
		$page = new $page_class($vpage, $template);
		$ret = $page->get_vpage_last_modified($dbc);

		return $ret;
	}


	protected function export_common() {
		$vpage = $this->get_vpage();
		$dbc = $this->get_dbc();

		$vpage_last_modified = $this->get_last_modified($this->get_vpage_template(), $vpage);
		$this->export('vpage_last_modified', $vpage_last_modified);


		// loading cache settings
		$settings_cache = new TCMS_Settings_Cache_DBC();
		if ($settings_cache->load_by_id($dbc, 1)) {
			$this->export('settings_cache', $settings_cache);
		} else {
			throw new Tangra_User_Exception('Cannot load cache settings');
		}


		// loading users for created by and last modified by
		$admin_user = new Admin_User_DBC();
		if ($admin_user->load_by_id($dbc, $vpage->get_created_by())) {
			$this->export('created_by', $admin_user->get_username());
		}
		if ($admin_user->load_by_id($dbc, $vpage->get_last_modified_by())) {
			$this->export('last_modified_by', $admin_user->get_username());
		}


		// loading categories that this page belongs to
		$categories = TCMS_VPage_Category_DBC::load_vpage_categories($dbc, $vpage->get_id());
		$this->export('categories', $categories);


		// loading menu items that are linked to this page (only of type TCMS_Menu_Item_VPage_DBC, "raw" links are not checked)
		$items_linking_to_vpage = TCMS_Menu_Item_VPage_DBC::load_items_linking_to_vpage($dbc, $vpage->get_id());
		$this->export('items_linking_to_vpage', $items_linking_to_vpage);
		$this->export('items_linking_to_vpage_count', count($items_linking_to_vpage));


		// loading current category (If any)
		$category_id = $this->get_transit_var('category', true);
		if ($category_id) {
			$category = new TCMS_Category_DBC();

			if (!$category->load_by_id($dbc, $category_id)) {
				throw new Tangra_Module_Exception('Cannot load TCMS_Category_DBC with id = '.$category_id);
			}

			$this->export('category', $category);
		}


		$cache_path = str_replace('/', '-', $vpage->get_path()).'-vp'.$vpage->get_id().'.html';
		$cache_file = $this->get__config()->get_scratch_dir().'tcms_cache/'.$cache_path;
		if(file_exists($cache_file)) {
			$this->export('cache_file', $cache_path);
			$this->export('cache_file_mtime', date('Y-m-d H:i:s', filemtime($cache_file)));
		}
	}


	protected function load_system_attribute($sa_export_name) {
		$dbc = $this->get_dbc();

		$rez = TCMS_VPage_System_Attribute_DBC::load_all_by_sa_export_name_vpage($dbc, $sa_export_name, $this->get_vpage()->get_id());
		if (count($rez)) {
			$ret = current($rez);
		} else {
			$ret = false;
		}

		return $ret;
	}


	protected function load_content_item($ci_export_name) {
		$dbc = $this->get_dbc();

		$ret = false;

		$ci = new TCMS_VPage_CI_DBC();
		if ($ci->load_ci_by_page_and_export_name($dbc, $this->get_vpage()->get_id(), $ci_export_name)) {
			$ret = $ci;
		}

		return $ret;
	}
}